package Eclass.Exam;

import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.lang.Math;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import login.UserModel;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import Candidate.CandidateForm;
import Eclass.EclassForm;
import Eclass.Score.ScoreForm;
import Forum.ForumThreadForm;
import Master.SchoolForm;
import Quartz.QuartzModel;
import Quartz.QuartzPlugin;

public class ExamAction extends Action{
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// TODO Auto-generated method stub
		ExamForm exForm = (ExamForm) form;
		ExamManager examManager = new ExamManager();
		HttpSession session = request.getSession(true);
		//System.out.println(exForm.getTask() + "\n\n");
		
		//-------------------------------------------------------------- Navigation ----------------------------------------------------------
				CandidateForm candidateForm = new CandidateForm();
				SchoolForm schoolForm = new SchoolForm();
				EclassForm eClassForm = new EclassForm();
				ForumThreadForm forumForm = new ForumThreadForm();
				ScoreForm scoreForm = new ScoreForm();
				
				if("updateCandidate".equalsIgnoreCase(exForm.getTask())) {
					candidateForm.getcModel().setRegisNo("01-13-12- 029");
					candidateForm.setTask("updateCandidate");
					
					System.out.println("Masuk update candidate di Exam");
					return mapping.findForward("candidate");
				}else if("manageTrainee".equalsIgnoreCase(exForm.getTask())) {	
					eClassForm.setTask("manageTrainee");
					return mapping.findForward("eclass");
				}else if("batch".equalsIgnoreCase(exForm.getTask())) {
					eClassForm.setTask("batch");
					return mapping.findForward("eclass");
				}else if("listExamPrep".equalsIgnoreCase(exForm.getTask())) {
					eClassForm.setTask("listExamPrep");
					return mapping.findForward("eclass");
				}else if("manageSchool".equalsIgnoreCase(exForm.getTask())) {
					schoolForm.setTask("manageSchool");
					return mapping.findForward("master");
		  		}else if("forumPage".equalsIgnoreCase(exForm.getTask())) {
					forumForm.setTask("forumPage");
					return mapping.findForward("forum");
				}else if("report".equalsIgnoreCase(exForm.getTask())) {
					scoreForm.setTask("getReport");
					return mapping.findForward("score");
				}
		//------------------------------------------------------------------------------------------------------------------------------
		
		String userId = ((UserModel)session.getAttribute("userLogin")).getUserid();
		String role = ((UserModel)session.getAttribute("userLogin")).getRole();
		int examPrepId = exForm.getListUjian().getExamPrepId();
		int batchClassId = exForm.getListUjian().getBatchClassId();
		int totalQuestion = exForm.getTotalQuestion();
		
		
		String[] tamp = exForm.getAnswer();
		String desc = "";
		String tamp_answer = "";
		
		//System.out.println(exForm.getTask() + "\n\n");
		
		// mulai ujian
		if("doExam".equals(exForm.getTask())) {
			//System.out.println("1\n\n");
			
			exForm.setCurrentQuestion(1);
			//exForm.setTotalQuestion(totalQuestion);
			exForm.getExamModel().setNo(1);
			
			// cek uda ada startHour atau belum
			if("".equalsIgnoreCase(exForm.getListUjian().getStartHour()) && "candidate".equalsIgnoreCase(role))
			{
				exForm.setListUjian(examManager.getExamSchedule(userId, role, true));
				System.out.println("start hour nya ga ada.... "+ exForm.getListUjian().getStartHour() +" ....\n\n");
				
				//---------------------------------------------Quartz
//				String examOpen, examClosed;
//				examOpen = exForm.getListUjian().getEndHour()
//						.replaceAll("-", ":");
//				examOpen = examOpen.replaceAll(" ", ":");
				

				QuartzPlugin qPlugin = new QuartzPlugin();
				QuartzModel quartzModel = new QuartzModel();

				String[] open = exForm.getListUjian().getEndHour().split(":");
				
//				System.out.println(examOpen);
				quartzModel.setUserId(userId);
				
				quartzModel.setExamPrepId(""+exForm.getListUjian().getExamPrepId());
				quartzModel.setDateClosed(open[0]);
				quartzModel.setMonthClosed(open[1]);
				quartzModel.setYearClosed(open[2]);
				quartzModel.setHourClosed(open[3]);
				quartzModel.setMinuteClosed(open[4]);
				quartzModel.setExamFor("ReloadCandidate");
				
				qPlugin.ActionCandidate(quartzModel);
				//-----------------------------------------------
			}
			
			// continue / mulai baru
			Integer tampTotalQuestion = examManager.getTotalQuestion(userId, examPrepId);
			//System.out.println("\n\n" + tampTotalQuestion);
			if(tampTotalQuestion == 0) {
				exForm.setTotalQuestion(examManager.generateSoal(userId, examPrepId, role));
				// insert exam_log
				examManager.insertExamLog(userId, examPrepId, "Start Exam");
				//exForm.setDoExam(false);
			}else {
				exForm.setTotalQuestion(tampTotalQuestion);
				// insert exam_log
				examManager.insertExamLog(userId, examPrepId, "Continue Exam");
				//exForm.setDoExam(true);
			}
		
			ExamModel exModel = new ExamModel();
			exModel = examManager.getQuestion(userId, exForm.getCurrentQuestion(), examPrepId, role);
			
			//System.out.println(exModel.getQuestion());
			
			if(exModel != null) {
//			try {
				String optionOfAnswer = exModel.getOptionOfAnswer();
				exForm.setQuestion(exModel.getQuestion());
				exForm.getExamModel().setQuestion(exModel.getQuestion());
				
				System.out.println(optionOfAnswer);
				
				exForm.setOptionOfAnswer(divideOptionOfAnswer(optionOfAnswer));
				
				if(exModel.getAnswer() != null) {
					//System.out.println("\n\njawaban " + exModel.getAnswer());
					String[] tamp2 = exModel.getAnswer().split("@");
					//System.out.println("\n\njawaban " + tamp2.length);
					exForm.setAnswer(tamp2);
				}
				
				exForm.setUanswerQuestion(examManager.getUnanswerQuestion(userId, examPrepId));
				
				session.setAttribute("doExam", "1");
//			} catch (Exception e) {
				// TODO: handle exception
//				exModel = null;
				//session.removeAttribute("doExam");
//			}
				
			} else {
				System.out.println("question null : doExam");
				session.removeAttribute("doExam");
			}
			
			System.out.println("cek 5");
			
			
			
			return mapping.findForward("startExam");
		}
		else if("goto".equals(exForm.getTask())) {
			
			if(exForm.getAnswer() != null) {
				// save/update answer
				exForm.getExamModel().setExamPrepId(examPrepId);
				exForm.getExamModel().setAnswer(concatAnswer(exForm.getAnswer()));
				examManager.updateAnswer(userId, exForm.getExamModel());
				
				System.out.println("\nselesai update jawaban\n\n");
			}else {
				// save/update answer
				exForm.getExamModel().setExamPrepId(examPrepId);
				exForm.getExamModel().setAnswer(null);
				examManager.updateAnswer(userId, exForm.getExamModel());
			}
			
			// ======= untuk isi exam log ===========
			desc += "Choose ";
			if(exForm.getExamModel().getAnswer() == null) {
				desc = desc + "nothing";
			} else {
				tamp_answer = (exForm.getExamModel().getAnswer()).replaceAll("@", ", ");
				desc = desc + tamp_answer;
			}
			desc = desc + " for no " + exForm.getExamModel().getNo() + ".";
			desc = desc + " Go to number " + exForm.getCurrentQuestion() + ".";
			
			examManager.insertExamLog(userId, examPrepId, desc);
			// ===========================================	
			
 				
			//System.out.println("goto 1 \n\n\n");
			exForm.setAnswer(null);
			
			exForm.setTotalQuestion(totalQuestion);
			exForm.setCurrentQuestion(exForm.getCurrentQuestion());
			exForm.getExamModel().setNo(exForm.getCurrentQuestion());
			//////exForm.setTotalQuestion(examManager.generateSoal("fanny.fh", 4));

			ExamModel exModel = new ExamModel();
			exModel = examManager.getQuestion(userId, exForm.getCurrentQuestion(), examPrepId, role);
			if(exModel != null) {
				exForm.getExamModel().setQuestion(exModel.getQuestion());
				exForm.setOptionOfAnswer(divideOptionOfAnswer(exModel.getOptionOfAnswer()));
				
				if(exModel.getAnswer() != null) {
					
					System.out.println("\n\njawaban " + exModel.getAnswer());
					String[] tamp2 = exModel.getAnswer().split("@");
					System.out.println("\n\njawaban " + tamp2.length);
					exForm.setAnswer(tamp2);
				}
				
				
				//exForm.setAnswer(tamp2);
				exForm.setUanswerQuestion(examManager.getUnanswerQuestion(userId, examPrepId));
				
				session.setAttribute("doExam", "1");
			} else {
				System.out.println("question null : goto");
				session.removeAttribute("doExam");
			}
			//String optionOfAnswer = exModel.getOptionOfAnswer();
			//exForm.setQuestion(exModel.getQuestion());
			
			
			return mapping.findForward("startExam");
		} else if("endExam".equals(exForm.getTask())) {
			if(exForm.getAnswer() != null) {
				// save/update answer
				exForm.getExamModel().setExamPrepId(examPrepId);
				exForm.getExamModel().setAnswer(concatAnswer(exForm.getAnswer()));
				examManager.updateAnswer(userId, exForm.getExamModel());
				
				System.out.println("\nselesai update jawaban\n\n");
			} else {
				// save/update answer
				exForm.getExamModel().setExamPrepId(examPrepId);
				exForm.getExamModel().setAnswer(null);
				examManager.updateAnswer(userId, exForm.getExamModel());
			}
			
			Double score = examManager.calculateScore(userId, examPrepId);
			if(score != 0.0) {
				score = Math.round(score * 100.0) / 100.0;
			} else {
				score = 0.0;
			}
			
			System.out.println("score : " + score + "\n\n");
			if("Trainee".equalsIgnoreCase(role)) {
				examManager.insertExamScore(batchClassId, score, userId, role);
				System.out.println("\n\nselesai insert nilai\n\n");
			} else if("candidate".equalsIgnoreCase(role)) {
				examManager.insertExamScore(batchClassId, score, userId, role);
			}
			
			// ======= untuk isi exam log ===========
			desc += "Choose ";
			if(exForm.getExamModel().getAnswer() == null) {
				desc = desc + "nothing";
			} else {
				tamp_answer = (exForm.getExamModel().getAnswer()).replaceAll("@", ", ");
				desc = desc + tamp_answer;
			}
			desc = desc + " for no " + exForm.getExamModel().getNo() + ".";
			desc = desc + " End Exam.";
			
			examManager.insertExamLog(userId, examPrepId, desc);
			// ===========================================	
			
			exForm.setTask("examResult");
			exForm.setResult(score);
			exForm.setQuestion(null);
			exForm.setOptionOfAnswer(null);
			
			//HttpServletResponse response=null;
			// response=ServletActionContext.getResponse();
//			 response.setHeader("Pragma", "no-cache");
//			 response.setHeader("Cache-Control", "no-cache");
//			 response.setHeader("Expires", "0"); 
			
			//session.setAttribute("doExam", true);
			session.removeAttribute("doExam");
			
			return mapping.findForward("startExam");
		} 
		
		//System.out.println("masuk 1 \n\n" );
		exForm.setListUjian(examManager.getExamSchedule(userId, role, false));
		exForm.setTask("exam");
		
		// ==================================
		Integer tampTotalQuestion2 = examManager.getTotalQuestion(userId, exForm.getListUjian().getExamPrepId());
		System.out.println("\n\n1111 " + tampTotalQuestion2);
		if(tampTotalQuestion2 == 0 || tampTotalQuestion2 == null) {
			exForm.setDoExam(false);
		} else {
			exForm.setDoExam(true);
		}
		
		
		//System.out.println("starthour " + exForm.getListUjian().getStartHour() + "\n\n");
		return mapping.findForward("startExam");
		
	}
	
	public List divideOptionOfAnswer(String optionOfAnswer) {
		String[] optionOfAnswer1 = optionOfAnswer.split("[@][#][$]");
		List list = new ArrayList();
		System.out.println("===="+optionOfAnswer1.length);
		
		for(int i=0; i<optionOfAnswer1.length; i++) {
			System.out.println("\n\noption " + optionOfAnswer1[i]);
			
			
			Map map = new HashMap();
			map.put("label1", optionOfAnswer1[i]);
			map.put("value1", optionOfAnswer1[i].substring(0,1).toUpperCase());

			list.add(map);
		}
		
		return list;
	}
	
	public String concatAnswer(String[] answer) {
		String result = "";
		//System.out.println("\n\n\nbanyak jawaban : " + answer.length + "\n\n\n");
		for (int i = 0; i < answer.length; i++) {
			result += answer[i];
			if(i < (answer.length - 1)) {
				result += "@";
			}
		}
		return result;
	}
	
}
